<?php

declare(strict_types=1);

namespace app\shop\controller\admin;

use think\Request;
use think\facade\Db;
use sheep\controller\Backend;
use sheep\exception\SheepException;
use sheep\library\Tree;
use app\shop\model\Withdraw as WithdrawModel;
use app\shop\model\WithdrawLog as WithdrawLogModel;
use app\shop\service\Withdraw as WithdrawLibrary;
use sheep\library\Operator;

/**
 * 提现
 */
class Withdraw extends Backend
{

    public function initialize()
    {
        $this->model = new WithdrawModel;
    }



    /**
     * 提现列表
     *
     * @return \think\Response
     */
    public function list()
    {
        $withdraws = $this->model->sheepFilter()->with(['user'])->order('id', 'desc')->paginate(request()->param('list_rows', 10));

        return success('获取成功', $withdraws);
    }

    /**
     * 提现日志
     *
     * @return \think\Response
     */
    public function log($id)
    {
        $logs = WithdrawLogModel::where('withdraw_id', $id)->with('oper')->order('id desc')->select()->toArray();
        // 解析操作人信息
        foreach ($logs as &$log) {
            $log['oper'] = Operator::info($log['oper_type'], $log['oper'] ?? null);
        }
        return success('获取成功', $logs);
    }

    public function handle($id)
    {
        $params = $this->request->param();
        $action = $params['action'] ?? null;
        $refuse_msg = $params['refuse_msg'] ?? '';
        if ($action == 'refuse' && !$refuse_msg) {
            throw new SheepException('请输入拒绝原因');
        }

        $ids = is_array($id) ? $id : explode(',', $id);
        foreach ($ids as $key => $id) {
            Db::startTrans();
            try {
                $withdraw = $this->model->lock(true)->findOrFail($id);
                $withdrawLib = new WithdrawLibrary($withdraw->user_id);

                switch ($params['action']) {
                    case 'agree':
                        $withdraw = $withdrawLib->handleAgree($withdraw);
                        break;
                    case 'agree&withdraw':
                        $withdraw = $withdrawLib->handleAgree($withdraw);
                        $withdraw = $withdrawLib->handleWithdraw($withdraw);
                        break;
                    case 'withdraw':
                        $withdraw = $withdrawLib->handleWithdraw($withdraw);
                        break;
                    case 'refuse':
                        $withdraw = $withdrawLib->handleRefuse($withdraw, $refuse_msg);
                        break;
                }

                Db::commit();
            } catch (SheepException $e) {
                Db::commit();       // 不回滚，记录错误日志
                throw new SheepException($e->getMessage());
            } catch (\Exception $e) {
                Db::rollback();
                throw new SheepException($e->getMessage());
            }
        }

        return success('处理成功');
    }
}
